package modes

import (
	"fmt"
	"time"
)

/*练习题记录*/
type Exer struct {
	Id    int64 `json:"exer_id" xorm:"id"`         //练习题id
	Uid   int64 `json:"exer_uid" xorm:"uid"`       //学员Id
	Cid   int64 `json:"exer_cid" xorm:"cid"`       //课程id
	Tid   int64 `json:"exer_tid" xorm:"tid"`       //题库id
	Stime int64 `json:"exer_s_time" xorm:"s_time"` //开始时间
	Etime int64 `json:"exer_e_time" xorm:"e_time"` //结束时间
	Score int64 `json:"exer_score " xorm:"score"`  //播放时长
	At    int64 `json:"exer_at" xorm:"at"`         //创建时间
}

func (this *Exer) TableName() string {
	return "exer"
}
func (this *Exer) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *Exer) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *Exer) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *Exer) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *Exer) Count(where string) (int64, error) {
	var val Exer
	return Db(0).Where(where).Count(&val)
}
func (this *Exer) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *Exer) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *Exer) where(fage, count, page int, where, field string) ([]Exer, error) {
	list := make([]Exer, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *Exer) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("uid = %d ", this.Uid)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}
